package com.audi.activity;

import java.util.ArrayList;

import lib.relay.RelayInterface;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.audi.BaseActivity;
import com.audi.R;
import com.audi.adapter.HomeBoxTutorialAdapter;
import com.audi.adapter.ListDeviceCardAdapterBottom;
import com.audi.adapter.ListDeviceCardAdapterTop;
import com.audi.adapter.ListPlaceCardAdapter;
import com.audi.box.objects.LocalData;
import com.audi.box.service.ConnectService;
import com.audi.dslv.DragSortController;
import com.audi.dslv.DragSortListView;
import com.audi.dslv.DragSortListView.DropListener;
import com.audi.dto.DeviceItem;
import com.audi.dto.PlaceItem;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.view.BaseDeviceDialog;
import com.audi.view.BasePlaceDialog;
import com.audi.view.DeviceUpdatePhoto;

public class HomeControlActivity extends BaseActivity implements ActionMessage {
	// private SimpleGestureFilter detector;
	// private SQLiteAsusNewHelper mSQLite = new SQLiteAsusNewHelper(this);
	public int conditon = 0;
	public DragSortListView listPlace;
	public static GridView listDeviceTop;
	public GridView listDeviceBot;
	public DeviceItem deviceSource, deviceDis;
	public double xMin, xMax, xMid, yMin, yMax, yMid;

	private ListPlaceCardAdapter listPlaceMem;
	public static ListDeviceCardAdapterTop listDeviceMemTop;
	private ListDeviceCardAdapterBottom listDeviceMemBot;
	private ArrayList<DeviceItem> listFavorite;
	public MyDragEventListener myDragEventListener = new MyDragEventListener();
	private DragSortController mControllerPlace;
	private ArrayList<PlaceItem> mListPlaceMember;
	public static ArrayList<DeviceItem> mListDeviceMemberTop, tmp;
	private ArrayList<DeviceItem> mListDeviceMemberBot;
	private SendMessage sendMessage = new SendMessage();
	public LinearLayout groupDevice;
	public LinearLayout targetLayout;
	private float xTop, yTop;
	private ImageButton btnDeviceCardDrawer;
	private TextView btnTabDevice, btnTabPlace;
	private boolean addDeviceFlag = true;
	private ImageButton btnAddDevicePlace;
	private ProgressDialog m_DlgProgress = null;
	public static final String TAG_HOMECONTROL = "[HomeControlActivity]";
	public static int numberDevice = 0;
	private DeviceUpdatePhoto mDeviceUpdatePhotoHomeControl;
	private HomeBoxTutorialAdapter mHomeboxTutorialAdapter;
	private ListView mTutorialDeviceList;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		// detector = new SimpleGestureFilter(this, this);
		setContentView(R.layout.activity_main);
		initActionBar();
//		try {
//			Log.d(LocalData.TAG_SERVICE,"try to start");
//			try{
////			startService(new Intent(this, ConnectService.class));
//				Log.d(LocalData.TAG_SERVICE,"inside try");
//				startService(new Intent(HomeControlActivity.this, ConnectService.class));
//			}
//			catch (Exception e)
//			{
//				Log.e(LocalData.TAG_SERVICE,""+e);
//			}
//		}
//		catch(Exception e)
//		{
//			Log.e(LocalData.TAG_SERVICE,"fail to start" + e);
//		}
		mDeviceUpdatePhotoHomeControl = new DeviceUpdatePhoto(this);
		// Activity co 2 tab: Device va Place
		/*
		 * Xu ly Device Drag: Buoc 1: Tao 2 gridview Tao them truong
		 * device.favorite de luu trang thai cac item cua device hien o tren.
		 * Buoc 2: Bat action Drag item tu grid o phia duoi, truyen IdDevice len
		 * gridview tren Get size cua Layout, de lay Position Buoc 3: Kiem tra
		 * cac truong hop khong the drag. Neu OK, cap nhat trang thai favorite
		 * cua item o gridview tren va gridview duoi.
		 * 
		 * Buoc 4: Refresh Data.
		 */
		initView();
		initListener();
	}

	public DropListener onDropPlace = new DropListener() {

		public void drop(int from, int to) {
			if (from != to) {
				PlaceItem s = (PlaceItem) mListPlaceMember.get(from);
				mListPlaceMember.remove(from);
				mListPlaceMember.add(to, s);
				listPlaceMem.notifyDataSetChanged();
			}

		}
	};

	private void initListener() {
		listDeviceBot
				.setOnItemLongClickListener(listSourceItemLongClickListener);
		listDeviceTop.setOnDragListener(myDragEventListener);
		targetLayout.setOnDragListener(myDragEventListener);
		listPlace.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				Intent intentDeviceCard = new Intent(HomeControlActivity.this,
						NewActivityPlaceInfo.class);
				Bundle bundleInfoPlace = new Bundle();

				PlaceItem item = mListPlaceMember.get(arg2);
				bundleInfoPlace.putSerializable("item", item);

				intentDeviceCard.putExtras(bundleInfoPlace);
				startActivity(intentDeviceCard);
			}
		});
		btnTabPlace.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				listPlace.setVisibility(View.VISIBLE);
				groupDevice.setVisibility(View.GONE);
				mTutorialDeviceList.setVisibility(View.GONE);
				btnTabDevice.setTextColor(Color.BLACK);
				btnTabPlace.setTextColor(Color.WHITE);
				btnTabDevice.setBackgroundResource(R.drawable.btn_tab_off_new);
				btnTabPlace.setBackgroundResource(R.drawable.btn_tab_on_new);
				// loadListPlace();
				mControllerPlace = new DragSortController(listPlace);
				mControllerPlace.setDragHandleId(R.id.lnl_drag);
				mControllerPlace.setRemoveEnabled(false);
				mControllerPlace.setSortEnabled(true);
				mControllerPlace.setDragInitMode(2);
				listPlace.setFloatViewManager(mControllerPlace);
//				listPlace.setOnTouchListener(mControllerPlace);
				listPlace.setDragEnabled(true);
				listPlace.setDropListener(onDropPlace);
				addDeviceFlag = false;
				CreateProgressDialog(getString(R.string.loading));
				updateDataPlace();

			}
		});
		btnTabDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				listPlace.setVisibility(View.GONE);
				groupDevice.setVisibility(View.VISIBLE);
				btnTabPlace.setTextColor(Color.BLACK);
				btnTabDevice.setTextColor(Color.WHITE);
				btnTabPlace.setBackgroundResource(R.drawable.btn_tab_off_new);
				btnTabDevice.setBackgroundResource(R.drawable.btn_tab_on_new);
				CreateProgressDialog(getString(R.string.loading));
				updateDataDevice();
				addDeviceFlag = true;
			}
		});

		btnAddDevicePlace.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (addDeviceFlag) {
					startActivity(new Intent(HomeControlActivity.this,
							NewDeviceActivity.class));
				} else {
					BasePlaceDialog addNewPlaceDialog = new BasePlaceDialog(
							HomeControlActivity.this);
					addNewPlaceDialog.selectPrivacyPlace();
				}

			}
		});
		mTutorialDeviceList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				mHomeboxTutorialAdapter.removeItem(position);
			}
		});

	}

	private void initView() {
		tempId = R.layout.action_bar_main;
		btnTabPlace = (TextView) findViewById(R.id.tab_place);
		btnTabDevice = (TextView) findViewById(R.id.tab_device);
		listPlace = (DragSortListView) findViewById(R.id.lv_place_tab);
		listDeviceBot = (GridView) findViewById(R.id.gridViewDeviceBot);
		listDeviceTop = (GridView) findViewById(R.id.gridView_deviceTop);
		groupDevice = (LinearLayout) findViewById(R.id.groupDevice);
		groupDevice.setVisibility(View.VISIBLE);
		btnAddDevicePlace = (ImageButton) findViewById(R.id.btn_menu_add_devices);
		mTutorialDeviceList = (ListView) findViewById(R.id.lv_tutorial_device_tab);
		listPlace.setVisibility(View.INVISIBLE);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int maxScreenY = displaymetrics.heightPixels;
		int maxScreenX = displaymetrics.widthPixels;
		xMin = 0;
		xMax = maxScreenX;
		xMid = (double) maxScreenX / 2; // Cac ti le man hinh chia duoc tu spec;
		yMin = ((double) maxScreenY) / 5.89;
		yMax = (double) maxScreenY / 1.4543;
		yMid = yMin + (double) maxScreenY / 3.8622;

		// Tao drag cho 2 gridview
		targetLayout = (LinearLayout) findViewById(R.id.layoutTarget);
		final String SOURCELISTTAG = "listSource";
		final String TARGETLISTTAG = "listTarget";
		final String TARGETLAYOUTTAG = "targetLayout";

		listDeviceBot.setTag(SOURCELISTTAG);
		listDeviceTop.setTag(TARGETLISTTAG);
		targetLayout.setTag(TARGETLAYOUTTAG);

		ArrayList<Integer> listTutorial = new ArrayList<Integer>();
		listTutorial.add(0);
		listTutorial.add(1);
		mHomeboxTutorialAdapter = new HomeBoxTutorialAdapter(this, listTutorial);
		mTutorialDeviceList.setAdapter(mHomeboxTutorialAdapter);

		// listDeviceTop.setVerticalScrollBarEnabled(false);
		// CreateProgressDialog(getString(R.string.loading));

	}

	public void updateDataDevice() {
		sendMessage.sendData(ActionMessage.getAllDeviceList, null,
				loadListDeviceHandler);

	}

	public void updateDataPlace() {
		sendMessage.sendData(ActionMessage.getAllPlaceList, null,
				loadListPlaceHandler);
	}

	public void loadListPlace(ArrayList<PlaceItem> listPlaceData) {
		try {
			listPlace.setVisibility(View.VISIBLE);
			mListPlaceMember = listPlaceData;
			if (mListPlaceMember != null && mListPlaceMember.size() > 0) {
				if (listPlaceMem == null) {
					listPlaceMem = new ListPlaceCardAdapter(this,
							mListPlaceMember, mDeviceUpdatePhotoHomeControl);
					listPlace.setAdapter(listPlaceMem);
				} else {
					listPlaceMem.swapItems(mListPlaceMember);
				}
			} else {
				Log.e("--NULLL-----", "------------NULLL--------------");
			}
		} catch (Exception ex) {
			Log.d("ex", "LOG" + ex);

		}
	}

	public void loadListDevice(ArrayList<DeviceItem> listDevice) {
		try {
			groupDevice.setVisibility(View.VISIBLE);
			listPlace.setVisibility(View.GONE);
			if (listDevice.size() > 0) {
				groupDevice.setVisibility(View.VISIBLE);
				mTutorialDeviceList.setVisibility(View.GONE);
				mListDeviceMemberTop = listDevice;
//				Log.d("Change device status","" + mListDeviceMemberTop.get(0).getDeviceName());
				if (mListDeviceMemberTop != null
						&& mListDeviceMemberTop.size() > 0) {
					if (listDeviceMemTop == null) {
						listDeviceMemTop = new ListDeviceCardAdapterTop(this,
								mListDeviceMemberTop, null);
						
						int i=0;
						for (i=0;i< mListDeviceMemberTop.size(); i++)
						{
							Log.d("Change device status1","ID: "+ listDeviceMemTop.getItem(i).getDeviceId() +" Name: "+listDeviceMemTop.getItem(i).getDeviceName() + " status: "+listDeviceMemTop.getItem(i).getDeviceStatus());
						}
						listDeviceTop.setAdapter(listDeviceMemTop);
						listDeviceTop.notify();
					} else {
						listDeviceMemTop.swapItems(mListDeviceMemberTop);
					}

				} else {
					Log.e("--NULLL-----", "1111111111111111111111111-");
				}
				mListDeviceMemberBot = new ArrayList<DeviceItem>();

				for (int i = listDevice.size() - 1; i >= 0; i--)
					mListDeviceMemberBot.add(listDevice.get(i));

				if (mListDeviceMemberBot != null
						&& mListDeviceMemberBot.size() > 0) {
					if (listDeviceMemBot == null) {
						listDeviceMemBot = new ListDeviceCardAdapterBottom(
								this, mListDeviceMemberBot, null);
						listDeviceBot.setAdapter(listDeviceMemBot);
					} else {
						listDeviceMemBot.swapItems(mListDeviceMemberBot);
					}
				} else {
					Log.e("--NULLL-----", "22222222222222222222");
				}
			} else {
				groupDevice.setVisibility(View.GONE);
				mTutorialDeviceList.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			Log.e("load list device", e.toString());
		}
	}

	protected class MyDragEventListener implements View.OnDragListener {
		@Override
		public boolean onDrag(View v, DragEvent event) {
			final int action = event.getAction();

			switch (action) {
			case DragEvent.ACTION_DRAG_STARTED:
				// All involved view accept ACTION_DRAG_STARTED for
				if (event.getClipDescription().hasMimeType(
						ClipDescription.MIMETYPE_TEXT_PLAIN)) {

					return true; // Accept
				} else {
					//
					return false; // reject
				}
			case DragEvent.ACTION_DRAG_ENTERED:

				return true;
			case DragEvent.ACTION_DRAG_LOCATION:

				return true;
			case DragEvent.ACTION_DRAG_EXITED:

				return true;
			case DragEvent.ACTION_DROP:

				ClipData.Item item = event.getClipData().getItemAt(0);

				if (v == targetLayout) {

					int x = (int) event.getX();
					int y = (int) event.getY();
					// toan do o vuong
					Log.d("x, Y", "" + x + " " + y); // keo vao
					Log.d("YmIN--YmAX", "" + yMin + " " + yMax); // size trung
					Log.d("XmIN--XmAX", "" + xMin + " " + xMax); // diem cua
					Log.d("Xmid--Ymid", "" + xMid + " " + yMid);
					// layout
					// chia man
					// hinh ra 4
					// phan
					// size max

					/*
					 * x = x + (int)xMax / 6;
					 * 
					 * y = y + (int)xMax / 6;
					 */
					Log.d("X--Y", "" + x + " " + y);
					int Case = 0;
					if ((x <= xMid) & (x > 0)) {
						if ((y <= yMid) & (y >= yMin))

							Case = 4;
						else if ((y >= yMid) & (y <= yMax))

							Case = 2;
					} else {
						if ((x <= xMax) & (x > xMid)) {
							if ((y <= yMid) & (y >= yMin))

								Case = 3;
							else if ((y >= yMid) & (y <= yMax))

								Case = 1;
						}
					}
					int idDevice = Integer.parseInt(item.getText() + "");
					DeviceItem item1;
					DeviceItem item2;
					DeviceItem item3;
					DeviceItem item4;

					if (mListDeviceMemberTop.size() > 2) {

						item1 = mListDeviceMemberTop.get(0);
						item2 = mListDeviceMemberTop.get(1);
						item3 = mListDeviceMemberTop.get(2);
						item4 = mListDeviceMemberTop.get(3);
						if ((idDevice == item1.getDeviceId())
								|| idDevice == item2.getDeviceId()
								|| idDevice == item3.getDeviceId()
								|| idDevice == item4.getDeviceId())
							return false;
						switch (Case) {
						case 4:

							updateDrag(idDevice, 4, item1.getDeviceId(), Case);

							break;
						case 3:
							updateDrag(idDevice, 3, item2.getDeviceId(), Case);

							break;
						case 2:

							updateDrag(idDevice, 2, item3.getDeviceId(), Case);

							break;
						case 1:
							updateDrag(idDevice, 1, item4.getDeviceId(), Case);

							break;

						}

					}

				} else {

					return false;
				}

			case DragEvent.ACTION_DRAG_ENDED:
				if (event.getResult()) {

				} else {
				}
				;
				return true;
			default:
				return false;

			}
		}

	}

	public void updateDrag(int idDeviceSource, int favoriteSource, int idDis,
			int Case) {
		listFavorite = new ArrayList<DeviceItem>();
		deviceSource = new DeviceItem();
		deviceDis = new DeviceItem();
		deviceSource.setDeviceId(idDeviceSource);
		deviceSource.setFavorite(favoriteSource);
		deviceDis.setDeviceId(idDis);
		deviceDis.setFavorite(0);
		listFavorite.add(0, deviceDis);
		listFavorite.add(1, deviceSource);
		Log.d("case, Name BOt Name TOp: ",
				Case + "  " + deviceSource.getDeviceId() + "  --- "
						+ deviceDis.getDeviceId());
		sendMessage.sendData(ActionMessage.UPDATE_FAVORITE_DEVICE,
				listFavorite, handlerUpdateFavorite);
	}

	public OnItemLongClickListener listSourceItemLongClickListener = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> l, View v, int position,
				long id) {

			// Selected item is passed as item in dragData
			DeviceItem item1 = mListDeviceMemberBot.get(position);
			ClipData.Item item = new ClipData.Item(item1.getDeviceId() + "");

			String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
			ClipData dragData = new ClipData(v.getTag() + "", clipDescription,
					item);
			// ClipData dragData = new ClipData(v.getId()+"",
			// clipDescription, item);
			Log.e("============", "======drfdf===" + v.getTag());

			DragShadowBuilder myShadow = new MyDragShadowBuilder(v);

			v.startDrag(dragData, // ClipData
					myShadow, // View.DragShadowBuilder
					item1.getDeviceId(), // Object myLocalState
					0); // flags

			return true;
		}
	};

	public static class MyDragShadowBuilder extends View.DragShadowBuilder {
		private static Drawable shadow;

		public MyDragShadowBuilder(View v) {
			super(v);
			shadow = new ColorDrawable(Color.LTGRAY);
		}

		@Override
		public void onProvideShadowMetrics(Point size, Point touch) {
			int width = getView().getWidth();
			int height = getView().getHeight();

			shadow.setBounds(0, 0, width, height);
			size.set(width, height);
			touch.set(width / 2, height / 2);

		}

		@Override
		public void onDrawShadow(Canvas canvas) {
			shadow.draw(canvas);
		}

	}

	protected void initActionBar() {
		btnDeviceCardDrawer = (ImageButton) findViewById(R.id.btn_devices_name_drawer);
		btnDeviceCardDrawer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
					mDrawerLayout.openDrawer(mDrawerList);					
				} else {
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			}
		});
	}

	@Override
	public void onRefreshData() {
		if (addDeviceFlag) {
			updateDataDevice();
		} else {
			updateDataPlace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (addDeviceFlag) {
			updateDataDevice();
		} else {
			updateDataPlace();
		}
	}

	/**
	 * loadListDeviceHandler
	 * 
	 * @see getlist device
	 */
	@SuppressLint("HandlerLeak")
	private Handler loadListDeviceHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							@SuppressWarnings("unchecked")
							ArrayList<DeviceItem> result = (ArrayList<DeviceItem>) msg
									.getData()
									.getSerializable(
											String.valueOf(ActionMessage.getAllDeviceList));
							numberDevice = result.size();
//							int i=0;
//							for (i=0;i<result.size(); i++)
//							{
//								Log.d("Change device status","ID: "+ result.get(i).getDeviceId() +" Name: "+result.get(i).getDeviceName());
//							}
							loadListDevice(result);
							DestroyProgressDialog();
						} else {
							// DestroyProgressDialog();
						}
					} catch (Exception e) {
						Log.e("load list device", e.toString());
						// DestroyProgressDialog();
					}
				}
			});
		}
	};

	/**
	 * addDeviceFinishHandler
	 * 
	 * @see add device finish, update UI
	 */
	@SuppressLint("HandlerLeak")
	private Handler addDeviceFinishHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							int de = msg.getData().getInt(
									String.valueOf(ActionMessage.addDevice));
							if (de > 0) {
								sendMessage
										.getListDevice(loadListDeviceHandler);
							}
							Toast.makeText(getApplicationContext(), "added", 1)
									.show();
						}
					} catch (Exception e) {
						// CreateWarningDialog("them that bai");
					}
				}
			});
		}
	};

	/**
	 * loadListDeviceHandler
	 * 
	 * @see get list place, update UI
	 */
	@SuppressLint("HandlerLeak")
	private Handler loadListPlaceHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							@SuppressWarnings("unchecked")
							ArrayList<PlaceItem> result = (ArrayList<PlaceItem>) msg
									.getData()
									.getSerializable(
											String.valueOf(ActionMessage.getAllPlaceList));
							loadListPlace(result);
							DestroyProgressDialog();
						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
	/**
	 * addPlaceFinishHandler
	 * 
	 * @see add place finish, update UI
	 */
	@SuppressLint("HandlerLeak")
	private Handler addPlaceFinishHandler = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							if (msg.getData().getInt(
									String.valueOf(ActionMessage.addPlace)) > 0) {
								// sendMessage
								// .getListDevice(loadListDeviceHandler);
							}
						}
					} catch (Exception e) {
					}
				}
			});
		}
	};

	/**
	 * onBackPressed
	 * 
	 * @see deinit P2P, finish
	 */
	@Override
	public void onBackPressed() {
		// CreateProgressDialog("Logout relay...");
		// RelayInterface.RelayDeInit();
		super.onBackPressed();
		onRefreshData();
	}

	/**
	 * CreateProgressDialog
	 * 
	 * @see create dialog
	 */
	
public void CreateProgressDialog(String strMessage) {
		m_DlgProgress = new ProgressDialog(this);
		m_DlgProgress.setTitle(null);
		m_DlgProgress.setMessage(strMessage);
		m_DlgProgress.setIndeterminate(true);
		m_DlgProgress.setCancelable(true);
		m_DlgProgress.show();
	}

	/**
	 * DestroyProgressDialog
	 * 
	 * @see destroy dialog
	 */
	public void DestroyProgressDialog() {
		if (m_DlgProgress != null)
			m_DlgProgress.dismiss();
	}

	@Override
	public void CBDeInit(boolean bValue) {
		if (bValue == true) {
			Log.d(TAG_HOMECONTROL,
					"[HomeControlActivity.java] DeInit Relay successfully.");
			RelayInterface.LogoutRelayS();
		} else {
			runOnUiThread(new Runnable() {
				public void run() {
					finish();
					Log.d(TAG_HOMECONTROL,
							"[HomeControlActivity.java] Failed to DeInit Relay.");
				}
			});

		}
	}

	@Override
	public void LogoutFinished(final boolean bValue) {
		runOnUiThread(new Runnable() {
			public void run() {
				finish();
			}
		});
	}

	/**
	 * renameDeviceFuntion
	 * 
	 * @see rename device
	 */
	public final void renameDeviceFuntion(DeviceItem deviceItem) {
		BaseDeviceDialog renameDevice = new BaseDeviceDialog(this);
		renameDevice.editNameDevice(deviceItem, handlerUpdateDevice);
	}

	// delete device
	public void deleteDeviceFuntion(DeviceItem deviceItem) {

		BaseDeviceDialog RemoveDialog = new BaseDeviceDialog(this);
		RemoveDialog.removeDevice(deviceItem, handlerUpdateDevice);

	}

	// change Photo device
	public void changePhotoDeviceFuntion(DeviceItem deviceItem) {
		mDeviceUpdatePhotoHomeControl.updatePhoto();
	}

	// change place device
	public void changePlaceDeviceFuntion(DeviceItem deviceItem) {
		BaseDeviceDialog changePlaceDialog = new BaseDeviceDialog(this);
		changePlaceDialog
				.showSelectPlaceDialog(deviceItem, handlerUpdateDevice);

	}

	/**
	 * renamePlaceFuntions
	 * 
	 * @param placeItem
	 *            PlaceItem
	 * @return
	 * @see rename place
	 */
	public void renamePlaceFuntion(PlaceItem placeItem) {
		BasePlaceDialog renamePlace = new BasePlaceDialog(this);
		renamePlace.editNamePlace(placeItem, handlerRenamePrivacyDeletePlace);
	}

	/**
	 * changeCapabilityOfPlace
	 * 
	 * @see change Capability Of Place
	 */
	public void changeCapabilityOfPlace(PlaceItem placeItem) {
		BasePlaceDialog renamePlace = new BasePlaceDialog(this);
		renamePlace.changeCapabilityOfPlace(placeItem,
				handlerRenamePrivacyDeletePlace);
	}

	/**
	 * 
	 * 
	 * @see delete place
	 */
	public void deletePlace(PlaceItem placeItem) {
		BasePlaceDialog renamePlace = new BasePlaceDialog(this);
		renamePlace.removePlace(placeItem, handlerRenamePrivacyDeletePlace);
	}

	/**
	 * handlerRenamePrivacyDeletePlace
	 * 
	 * @see update UI place
	 */
	@SuppressLint("HandlerLeak")
	private Handler handlerRenamePrivacyDeletePlace = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							if (msg.getData().getInt(
									String.valueOf(ActionMessage.renamePlace)) > 0
									|| msg.getData()
											.getInt(String
													.valueOf(ActionMessage.changeCapabilityPlace)) > 0
									|| msg.getData()
											.getInt(String
													.valueOf(ActionMessage.deletePlace)) > 0) {
								sendMessage.getListPlace(loadListPlaceHandler);
							} else if (msg.getData().getInt(
									String.valueOf(ActionMessage.renamePlace)) == 0) {
								BasePlaceDialog renamePlaceDialog = new BasePlaceDialog(
										HomeControlActivity.this);
								renamePlaceDialog.showNoticePlace();
							}
						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
	/**
	 * handlerRenamePrivacyDeletePlace
	 * 
	 * @see update UI place
	 */
	@SuppressLint("HandlerLeak")
	private Handler handlerUpdateDevice = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							// status
							if (msg.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_DEVICE)) > 0) {
								Log.d("update device", "OK!!!!");
								CreateProgressDialog(getString(R.string.loading));
								sendMessage
										.getListDevice(loadListDeviceHandler);
							}

						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler handlerUpdateFavorite = new Handler() {

		public void handleMessage(final Message msg) {
			runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							// status
							if (msg.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_FAVORITE_DEVICE)) > 0) {
								Log.d("update favorite device", "OK!!!!");
							}
							CreateProgressDialog(getString(R.string.loading));
							sendMessage.getListDevice(loadListDeviceHandler);

						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
	/**
	 * onActivityResult
	 * 
	 * @see call back device update photo
	 */

	int tempActionResult;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent myIntent = new Intent(this, ActivityReviewImageCrop.class);
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 555) {
			mDeviceUpdatePhotoHomeControl.dimissUpdate();
			Log.d("start crop", "dgfgfdgfdgdf");
			tempActionResult = 0;
		}
		if (resultCode == RESULT_OK) {
			// user is returning from capturing an image using the camera
			if (requestCode == mDeviceUpdatePhotoHomeControl.cameraCapture) {
				mDeviceUpdatePhotoHomeControl
						.performcrop(mDeviceUpdatePhotoHomeControl.getPicUri());
				Log.d("start crop", "crop crop crop");
				tempActionResult = 1;
			} else if (requestCode == mDeviceUpdatePhotoHomeControl.picCrop) {
				myIntent.putExtra("Req",
						mDeviceUpdatePhotoHomeControl.getstatus());
				// myIntent.putExtra("activity",mActivity.getApplicationContext());
				this.startActivityForResult(myIntent, 555);

				Log.d("start crop", "reviview=====-''/////");
				tempActionResult = 0;
			}
			if (requestCode == mDeviceUpdatePhotoHomeControl.pickFromFile) {
				tempActionResult = 2;
				mDeviceUpdatePhotoHomeControl.setPicUri(data.getData());
				mDeviceUpdatePhotoHomeControl
						.performcrop(mDeviceUpdatePhotoHomeControl.getPicUri());
				Log.d("start crop", "pick  form file=====- " + tempActionResult);

			}
		} else {
			Log.d("close ", "======== close" + tempActionResult);
			// Toast.makeText(activity, "sssss", Toast.LENGTH_LONG).show();
			if (tempActionResult == 1) {
				mDeviceUpdatePhotoHomeControl.camphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
			}
			if (tempActionResult == 2) {
				// upPhoto.performcrop(upPhoto.getPicUri());
				mDeviceUpdatePhotoHomeControl.picphoto();
				Log.d("stop", "''/////" + tempActionResult);
				tempActionResult = 0;
				// this.finish();
			}
		}
	}
}
